<template>
	<view class="container">
		<view class="main">
			<view class="list">
				<u-list :height="listHeight" @scrolltolower="scrolltolower">
					<view v-for="(bill, index) in billList" :key="index" class="imgBox">
						<!-- <u-image :src="`data:image/png;base64,${bill.img}`" width="670rpx" mode="aspectFit"
							@click="previewBase64Image(bill.img)"></u-image> -->
						<u-image :src="`data:image/png;base64,${bill.img}`" width="670rpx" mode="aspectFit">
							<!-- 先不传递点击事件 -->
						</u-image>
					</view>
					<u-loadmore v-if="billList.length>0" :status="dataTip" loadmore-text="上滑加载更多" />
				</u-list>
			</view>
		</view>
		<!-- 底部操作栏 -->
		<view class="footer">
			<u-button type="primary" text="发送至邮箱" @click="openModal"></u-button>
		</view>
		<u-modal ref="editModal" title="发送至邮箱" :show="showEditModal" :mask-close-able="false" :showCancelButton='true'
			@cancel='showEditModal=false' @confirm="getEmailPicFun" :close-on-click-modal="false">
			<u-form :model="editData" ref="loginForm">
				<u-form-item borderBottom>
					<u-radio-group v-model="editData.selectedFormat">
						<u-radio :customStyle="{marginRight: '16px'}" v-for="(item, index) in formatList"
							:key="item.value" :label="item.name" :name="item.value" :disabled="item.disabled">
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<!-- 邮箱输入框 -->
				<u-form-item label="邮箱" borderBottom>
					<u-input v-model="editData.email" placeholder="请输入邮箱"></u-input>
				</u-form-item>
				<!-- 帮助提示 -->
				<view class="help-section">
					<!-- <view class="help-title">
				    <u-icon name="info-circle" color="#1677ff" size="20" class="help-icon"></u-icon>
				    <text>帮助</text>
				  </view> -->
					<view class="help-list">
						<view class="help-item">
							<u-icon name="checkmark-circle" color="#1677ff" size="16" class="help-item-icon"></u-icon>
							<text>票据文件会在24小时后发送至您提供的邮箱中，请及时查收，如未收到邮件请登录网站https://nontax.hebcz.cn/的票据下载专题下载票据。</text>
						</view>
						<view class="help-item">
							<u-icon name="checkmark-circle" color="#1677ff" size="16" class="help-item-icon"></u-icon>
							<text>电子一般缴款书暂不支持PDF、OFD、XML格式的票据。</text>
						</view>
					</view>
				</view>
			</u-form>
		</u-modal>
		<slider-captcha v-show="isSliderShow" :frontimg="picObj.slidingImage" :backimg="picObj.backImage"
			:yHeight="picObj.yHeight" :maskclose="true" :randNum="telRandom" @onRefresh="getEmailPicFun"
			@onSuccess="postEmailFun" @onClose="handClose" @onMoveEnd="handleSliderMoveEnd" />
	</view>
</template>

<script>
	import {
		postShow,
		postEmail
	} from '@/api/ticketApi.js'
	import {
		getEmailPic,
		checkeamilcapcode,
		postSend
	} from '@/api/api.js'
	import SliderCaptcha from '@/pages/compoents/slideVue.vue';
	export default {
		components: {
			SliderCaptcha
		},
		data() {
			return {
				listHeight: uni.getSystemInfoSync().windowHeight - 90,
				formatList: [{
					name: 'PNG',
					value: 1,
					disabled: false,
				}, {
					name: 'PDF',
					value: 2,
					disabled: false,
				}, {
					name: 'OFD',
					value: 3,
					disabled: false,
				}, {
					name: 'XML',
					value: 4,
					disabled: false,
				}],
				isSliderShow: false,
				showEditModal: false,
				picObj: {
					slidingImage: '',
					backImage: '',
					capcode: '',
					yHeight: 0
				},
				editData: {
					selectedFormat: 1,
					email: '',
					randNum: ''
				},
				telRandom: 0, //请求验证码的随机码
				tips: '',
				itemData: {},
				dataTip: 'loadmore', //加载前值为loadmore，加载中为loading，没有数据为nomore
				currentPage: 1,
				pageSize: 5,
				billList: []
			}
		},
		created() {
			console.log('用户信息', uni.getStorageSync('userInfo'))
			const userInfo = uni.getStorageSync('userInfo')
			this.editData.email = userInfo.email || ''
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			this.itemData = JSON.parse(decodeURIComponent(option.item))
			console.log(this.itemData); //打印出上个页面传递的参数。
			if (this.itemData.billTypeId == 1230) {
				for (let i = 1; i < this.formatList.length; i++) {
					this.formatList[i].disabled = true //从第一位开始
				}
			}
			this.onSearch()
		},
		methods: {
			// 预览base64图片主方法
			previewBase64Image(base64Data) {
				// 1. 处理base64数据（去掉前缀，如"data:image/png;base64,"）
				// 2. 生成临时文件路径（微信小程序本地临时路径格式）
				const filePath = wx.env.USER_DATA_PATH + '/bill_image.png'; // 固定格式，后缀根据图片类型修改（如.jpg/.png）

				// 3. 获取文件系统管理器
				const fs = wx.getFileSystemManager();

				try {
					// 4. 将base64写入本地文件
					fs.writeFile({
						filePath: filePath,
						data: base64Data,
						encoding: 'base64', // 必须指定编码为base64
						success: () => {
							// 5. 写入成功后，调用保存图片API
							this.previewImage(filePath);
						},
						fail: (err) => {
							console.error('写入文件失败：', err);
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					});
				} catch (e) {
					console.error('处理base64出错：', e);
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			},
			previewImage(filePath) {
				// 1. 显示加载中提示
				uni.showLoading({
					title: '加载中...',
					mask: true // 防止用户重复点击
				});

				// 2. 由于base64图片无需网络请求，可直接调用预览（若图片过大，仍需短暂加载）
				wx.previewImage({
					current: filePath,
					urls: [filePath],
					showmenu: true,
					success: () => {
						// 3. 预览成功后关闭加载提示
						uni.hideLoading();
					},
					fail: (err) => {
						// 4. 失败时也关闭加载提示，并提示错误
						uni.hideLoading();
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
						console.error('预览失败：', err);
					}
				});
			},
			async getEmailPicFun() {
				// 邮箱正则表达式（通用规则：支持字母、数字、常见符号及多级域名）
				const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
				if (this.editData.selectedFormat != 1 && this.itemData.billTypeId == 1230) {
					return uni.$u.toast('电子一般缴款书暂不支持PDF、OFD、XML格式的票据。');
				}
				if (this.editData.email == '') {
					return uni.$u.toast('请输入邮箱');
				}
				if (!emailReg.test(this.editData.email)) {
					return uni.$u.toast('请输入正确的邮箱地址');
				}
				try {
					uni.showLoading({
						title: '加载中'
					})
					const res = await getEmailPic()
					console.log('222', res)
					if (res.data.result == 0) {
						this.picObj = {
							...res.data,
							backImage: 'data:image/png;base64,' + res.data.backImage,
							slidingImage: 'data:image/png;base64,' + res.data.slidingImage
						}
						this.telRandom = 0 // 打开前重置
						this.isSliderShow = true
						this.showEditModal = false
						uni.hideLoading()
					} else {
						uni.hideLoading()
						uni.$u.toast(res.data.message || '获取验证码失败！');
					}
				} catch (error) {
					uni.hideLoading()
					uni.$u.toast(res.data.message || '获取验证码失败！');
				}
			},
			async handleSliderMoveEnd(moveX) {
				console.log('--', moveX)
				try {
					const res = await checkeamilcapcode({
						xpos: moveX,
						capcode: this.picObj.capcode,
					})
					if (res.data.result == 0) {
						this.telRandom = res.data.randNum
					} else {
						this.telRandom = Math.floor(Math.random() * 1000)
						uni.$u.toast(res.data.message || '验证失败！');
					}
				} catch (error) {
					this.telRandom = Math.floor(Math.random() * 1000)
					uni.$u.toast(res.data.message || '验证失败！');
				}
			},
			async postEmailFun() {
				this.showEditModal = true
				this.isSliderShow = false
				// 模拟向后端请求验证码
				uni.showLoading({
					title: '正在发送邮件'
				})
				try {
					const params = {
						email: this.editData.email,
						einvoiceCode: this.itemData.einvoiceCode,
						einvoiceNumber: this.itemData.einvoiceNumber,
						randomNumber: this.itemData.randomNumber,
						randNum: this.telRandom
					}
					const res = await postEmail(params)
					if (res.data.result == 0) {
						uni.hideLoading();
						uni.$u.toast('邮件已发送');
					} else {
						uni.hideLoading();
						uni.$u.toast(res.data.message || '发送邮件失败！');
					}
				} catch (error) {
					uni.$u.toast(res.data.message || '发送邮件失败！');
				}
			},
			handClose() {
				this.isSliderShow = false
			},
			openModal() {
				if (this.billList.length == 0) {
					return this.$u.toast('票据正在传输中请稍后再查');
				}
				this.showEditModal = true
			},
			async onSearch() {
				uni.showLoading({
					title: '查询中'
				})
				this.currentPage = 1
				this.billList = []
				const params = {
					einvoiceCode: this.itemData.einvoiceCode,
					einvoiceNumber: this.itemData.einvoiceNumber,
					randomNumber: this.itemData.randomNumber,
					pageIndex: this.currentPage
				}
				const res = await postShow(params)
				console.log('res', res)
				if (res.data.result == 0) {
					if (res.data.totalPages <= this.currentPage) {
						this.dataTip = 'nomore'
					}
					this.billList = res.data.imgList || []
					if (this.billList.length == 0) {
						return this.$u.toast('票据正在传输中请稍后再查');
					}
					uni.hideLoading()
				} else {
					this.$u.toast(res.data.message || '接口错误');
					uni.hideLoading()
				}
			},
			scrolltolower() {
				if (this.dataTip == 'nomore' || this.dataTip == 'loading') {
					return
				}
				this.currentPage += 1
				console.log('daodile', this.currentPage)
				this.loadmore();
			},
			async loadmore() {
				this.dataTip = 'loading'
				const params = {
					einvoiceCode: this.itemData.einvoiceCode,
					einvoiceNumber: this.itemData.einvoiceNumber,
					randomNumber: this.itemData.randomNumber,
					pageIndex: this.currentPage
				}
				const res = await postShow(params)
				if (res.data.result == 0) {
					console.log('res', res)
					this.billList = this.billList.concat(res.data.imgList)
					if (res.data.totalPages <= this.currentPage) {
						this.dataTip = 'nomore'
					} else {
						this.dataTip = 'loadmore'
					}
				} else {
					this.$u.toast(res.message || '接口错误');
				}
			},
		}
	}
</script>

<style>
	.container {
		font-family: 'Inter', system-ui, sans-serif;
		background-color: #F2F3F5;
		color: #1D2129;
		min-height: 100vh;
		max-width: 750rpx;
		margin: 0 auto;
		position: relative;
	}

	.main {
		/* padding-bottom: 160rpx; */
	}

	/* 功能列表样式 */
	.list {
		padding: 30rpx 40rpx;
	}

	/* 底部样式 */
	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		max-width: 750rpx;
		margin: 0 auto;
		background-color: #FFFFFF;
		border-top: 1px solid #E5E6EB;
		padding: 24rpx 40rpx;
		z-index: 10;
	}

	.imgBox {
		margin-bottom: 30rpx;
		width: 100%;
		border-radius: 20rpx;
	}

	/* 帮助区域样式 */
	.help-section {
		background-color: rgba(22, 119, 255, 0.05);
		border-radius: 20rpx;
		padding: 30rpx;
		margin-top: 60rpx;
	}

	.help-title {
		font-size: 28rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
	}

	.help-icon {
		margin-right: 15rpx;
	}

	.help-list {
		font-size: 26rpx;
		color: #666666;
	}

	.help-item {
		display: flex;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.help-item:last-child {
		margin-bottom: 0;
	}

	.help-item-icon {
		margin-right: 15rpx;
		margin-top: 5rpx;
	}
</style>